﻿using System.Diagnostics;
using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
namespace CambiarFondoTask
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        /// 

        private string url;

        public string Url
        {
            get { return url; }
            set { url = value; }
        }

        private  IReadOnlyList<Windows.Storage.IStorageFile> l;

        private  IReadOnlyList<Windows.Storage.IStorageFile> List
        {
            get { return l; }
            set { l = value; }
        }
        

        static ScheduledAgent()
        {
            // Subscribe to the managed exception handler
            Deployment.Current.Dispatcher.BeginInvoke(delegate
            {
                Application.Current.UnhandledException += UnhandledException;
            });
        }

        /// Code to execute on Unhandled Exceptions
        private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                Debugger.Break();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
           
            CambiarFondo();
           
        }

        private async void CambiarFondo()
        {
            await getFotosDescargadas();
            LockHelper(Url, false);
        }


        private async Task getFotosDescargadas()
        {
            var localfolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            var folderToSave = await localfolder.CreateFolderAsync("shared", Windows.Storage.CreationCollisionOption.OpenIfExists);
            var folderToSave2 = await folderToSave.CreateFolderAsync("transfers", Windows.Storage.CreationCollisionOption.OpenIfExists);
            var files = await folderToSave2.GetFilesAsync();
            List = files;
            List.OrderByDescending(async O=> ( await O.GetBasicPropertiesAsync()).ItemDate);
            
            if (files.Count == 0)
                Abort();
            Random r = new Random();
            var aux =  r.Next(1, files.Count);
            while (true)
            {
                var pa = files[aux].Path;
                var prop = await files[aux].GetBasicPropertiesAsync();
               
                if (prop.Size > 0)
                {
                    Url = getFileName(pa);
                   
                    break;
                }
                else {
                    aux = r.Next(1, files.Count);                    
                }
            }
        }


        private async void LockHelper(string filePathOfTheImage, bool isAppResource)
        {
            try
            {
                    var schema = isAppResource ? "ms-appx:///" : "ms-appdata:///Local/";
                    var uri = new Uri(schema + "shared/transfers/" + filePathOfTheImage, UriKind.RelativeOrAbsolute);
                   
                Windows.Phone.System.UserProfile.LockScreen.SetImageUri(uri);
                    
                ShellToast st = new ShellToast();
                st.Title = "Fondo de Pantalla";
                st.Content = "ha sido actualizado!";
                st.Show();


                updateTile();
                NotifyComplete();


            }
            catch (System.Exception ex)
            {
             
            }
        }

        private string getFileName(string transferFileName)
        {
            transferFileName = transferFileName.Replace(@"\", @"/");

            string downloadFile = transferFileName.Substring(transferFileName.LastIndexOf("/") + 1);
            return downloadFile;
        }



        private void updateTile()
        {
            var tile = Microsoft.Phone.Shell.ShellTile.ActiveTiles.First();
            var cdata = new Microsoft.Phone.Shell.CycleTileData();
           // getFotosDescargadas();
            List<Uri> lastImages = new List<Uri>();

            int counter = 1;
            for (int i = 0; i < List.Count; i++)
            {
                if (counter == 9)
                    break;
                var url = List[i].Path.Replace(@"\", @"/");
                url = getFileName(url);

                var schema = "isostore:/";
                var uri = new Uri(schema + "shared/Shellcontent/" + url, UriKind.RelativeOrAbsolute);

                lastImages.Add(uri);
                counter++;
            }



            cdata.CycleImages = lastImages;
            tile.Update(cdata);
        }
    
    }


    
}